FormOp = {
    //layui加载项
    layuiList: ['layer', 'element', 'form', 'table', 'laydate', 'jquery', 'formSelects', 'jquery', 'util', 'select', 'select2'],
    //工具条
    toolbar: "#zmn-table-tool",
    //表格table的url数据地址
    taleUrl: "/report/collectionpayment/provider/loadData.action",
    //表格lay-filter
    tableElem: "zmn-table",
    //查询按钮
    qureyBtn: "form-submit-btn",
    exportUrl: "/report/collectionpayment/provider/export.action",
    formSelects: null,
    //查询条件
    queryParam: [],
    //查询条件区域form
    form: null,
    isFirstQuery: true,
    init: function (exports) {
        //FormOp.loadLayUi();
        FormOp.initLayUiOpt();
        exports('oms_report_provider_list', {});
    },
    /**
     * 初始化layui的对象
     */
    initLayUiOpt: function () {
        FormOp.$ = layui.$;
        FormOp.$http = layui.$http;
        FormOp.element = layui.element;
        FormOp.layer = layui.layer;
        FormOp.select = layui.select;
        FormOp.select2 = layui.select2;
        FormOp.formSelects = layui.formSelects;
        FormOp.table = layui.table;
        FormOp.form = layui.form;
        FormOp.laydate = layui.laydate;
        FormOp.util = layui.util;
        FormOp.baseInit();
        FormOp.setEvent();
        FormOp.tableInit();
    },
    /**
     * 引入layui
     */
    loadLayUi: function () {

    },
    /**
     * 初始化
     */
    baseInit: function () {
        var nowDate = new Date();
        var currentDate = new Date();
        var monthDateStart = currentMonthFirst(nowDate);
        var startDateDefault = FormOp.util.toDateString(monthDateStart, "yyyy-MM-dd");
        var endDateDefault = FormOp.util.toDateString(currentDate, "yyyy-MM-dd");
        FormOp.laydate.render({
            elem: "#accountTime", //指定元素
            trigger: 'click',
            range: true,
            value: startDateDefault + ' - ' + endDateDefault
        });
        FormOp.laydate.render({
            elem: "#time", //指定元素
            trigger: 'click',
            range: true,
            value: ""
        });
        FormOp.queryParam = {};
        FormOp.queryParam["accountTimeStart"] = FormOp.util.toDateString(startDateDefault, "yyyy-MM-dd") + " 00:00:00";
        FormOp.queryParam["accountTimeEnd"] = FormOp.util.toDateString(endDateDefault, "yyyy-MM-dd") + " 23:59:59";
        FormOp.queryParam["plat"] = FormOp.$("#plat").val();
        // 服务商类型暂时写死为1
        FormOp.queryParam["spCompanyType"] = "1";
        FormOp.formSelects.config(null, {
            keyName: 'text'
        }, false);
    },
    /**
     * 绑定事件
     */
    setEvent: function () {
        FormOp.form.on('submit(' + FormOp.qureyBtn + ')', FormOp.doQuery);
        var COMPANY_LIST_URL = '/company/list/query.action';
        FormOp.initSelect2Event("fcCompanyId", "230", COMPANY_LIST_URL);
        FormOp.initSelect2Event("spCompanyId", "130", COMPANY_LIST_URL);
        FormOp.initSelect2Event("customerId", "2", COMPANY_LIST_URL);
        var COMMON_SELECT_URL = "/report/collectionpayment/getSelectData.action";
        FormOp.initSelectEvent("orderKeep", COMMON_SELECT_URL + "?type=orderKeep");
        FormOp.initFormSelects("customerSettleStatus", COMMON_SELECT_URL + "?type=customerBillStatus");
        FormOp.initFormSelects("partBillStatus", COMMON_SELECT_URL + "?type=partBillStatus");
        FormOp.initFormSelects("settlementType", COMMON_SELECT_URL + "?type=settlementType");
        FormOp.table.on('toolbar(zmn-table)', FormOp.doExport);
        FormOp.form.on('submit(zmn-form-reset)', FormOp.doReset);

    },
    /**
     * 查询按钮
     */
    doQuery: function (data) {
        //验证
        //FormOp.doVerify();
        FormOp.buildQueryField(data.field);
        FormOp.tableReload();
        //FormOp.doAjax(FormOp.taleUrl, FormOp.queryParam, FormOp.queryCallBack);
        return false;
    },
    /**
     * 表格刷新数据
     */
    tableReload: function () {
        FormOp.tableObj.reload({
            where: FormOp.queryParam,
            page: {curr: 1}
        });
    },
    /**
     * 构建查询字段
     * @param data
     */
    buildQueryField: function (data) {
        FormOp.queryParam = null;
        FormOp.queryParam = data;
        //alert(JSON.stringify(params))
        for (var fieldKey in FormOp.queryParam) {
            if (FormOp.queryParam[fieldKey] === "") {
                //delete FormOp.queryParam[fieldKey];
            }
        }
        if (FormOp.queryParam["time"]) {
            let timeSpan = FormOp.queryParam["time"].split(' - ');
            FormOp.queryParam["manageStatementTimeStart"] = timeSpan[0] + " 00:00:00";
            FormOp.queryParam["manageStatementTimeEnd"] = timeSpan[1] + " 23:59:59";
            FormOp.queryParam["time"] = '';
        } else {
            FormOp.queryParam["manageStatementTimeStart"] = "";
            FormOp.queryParam["manageStatementTimeEnd"] = "";
        }
        if (FormOp.queryParam["accountTime"]) {
            var timeSpan = FormOp.queryParam["accountTime"].split(' - ');
            FormOp.queryParam["accountTimeStart"] = timeSpan[0] + " 00:00:00";
            FormOp.queryParam["accountTimeEnd"] = timeSpan[1] + " 23:59:59";
            FormOp.queryParam["accountTime"] = '';
        } else {
            FormOp.queryParam["accountTimeStart"] = "";
            FormOp.queryParam["accountTimeEnd"] = "";
        }
        // 服务商类型暂时写死为30
        FormOp.queryParam["spCompanyType"] = "30";
        return FormOp.queryParam;
    },
    /**
     * 验证
     */
    doVerify: function () {
        FormOp.form.verify({
            textveify: function (value, item) { //value：表单的值、item：表单的DOM对象
                if (value.length > 50) {
                    return "字符不能超过50";
                }
            }
        });
    },
    /**
     * 执行ajax请求
     * @param url
     * @param dataParam
     * @param callback
     */
    doAjax: function (url, dataParam, callback) {
        FormOp.$.ajax({
            type: 'POST',
            url: url,//发送请求
            data: dataParam,
            dataType: "json",
            success: callback,
            error: function (result) {
                layer.msg("操作失败，请联系管理员！");
            }
        });
    },
    /**
     * 查询回调方法，重绘tale数据
     * @param result
     */
    queryCallBack: function (data) {
        FormOp.refreshTable(data);
    },
    /**
     * 重置按钮
     */
    doReset: function () {
        location.reload();
    },
    /**
     * ajax查询结果之后通过方法渲染layui的数据表格
     * 之所以用ajax加载数据，是因为框架中有security，需要token验证，layui原生的自动加载没有办法设置token
     * @param dataResult
     */
    refreshTable: function (dataResult) {

    },
    /**
     * 初始化table
     */
    tableInit: function () {
        FormOp.options = {
            elem: "#" + FormOp.tableElem,
            cols: TableOP.cols,
            url: FormOp.taleUrl,
            height: "full-200",
            page: true,
            limit: 50,
            loading: true,
            toolbar: true,
            limits: [50, 100, 200],
            where: FormOp.queryParam,
            request: {
                pageName: 'pageIndex',  //页码的参数名称，默认：page
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            },
            response: {
                statusCode: 200
            },
            done: function (res) {
                //添加按钮
                $("div[lay-event='LAYTABLE_EXPORT']").attr('lay-event', 'CUSTOM_EXPORT');
                let totalLineRow = $("tr[data-index='0']");
                if (totalLineRow) {
                    $("tr[data-index='0']").css('background-color', 'rgb(242, 242, 242)');
                }
            }
        };
        //FormOp.table.init(FormOp.tableElem,FormOp.options);
        FormOp.tableObj = FormOp.table.render(FormOp.options);
    },
    /**
     * 下拉框事件
     * @param elemId 下拉框id
     * @param actionUrl 下拉框地址
     */
    initSelectEvent: function (elemId, actionUrl) {
        FormOp.select.render({
            elem: '#' + elemId,
            url: actionUrl
        });
    },
    /**
     * 初始化select2下拉框
     * @param ele
     * @param type
     * @param companyListUrl
     */
    initSelect2Event: function (ele, type, companyListUrl) {
        FormOp.select2.initRemote({
            el: '#' + ele,
            url: companyListUrl,
            getParams: function (params) {
                return {
                    name: params.term,
                    type: type,
                    plat: $('#plat').val(),
                };
            },
            processor: function (data) {
                return data.map((item) => {
                    item.id = item.value;
                    item.disabled = false;
                    return item;
                });
            },
            formatRepo: formatRepoForCompany
        });
    },
    initFormSelects: function (ele, companyListUrl) {
        FormOp.formSelects.data(ele, 'server', {
            url: companyListUrl
        });
    },
    doExport: function (obj) {
        if (obj.event == "CUSTOM_EXPORT") {
            let that = this;
            let ele = that.querySelector('i');
            zmnLayUtil.toggleLoading(ele);
            that.setAttribute('lay-event', '');
            zmnUtil.download(FormOp.exportUrl, obj.config.where, "服务商/客户收付款对账表" + new Date().toISOString() + '.xlsx', (res) => {
                that.setAttribute("lay-event", 'CUSTOM_EXPORT');
                zmnLayUtil.toggleLoading(ele);
            });
        }
    }
};
/**
 * 表格字段
 * @type {*[][]}
 */
TableOP = {
    cols: [[
        {
            field: 'orderId',
            title: '工单号',
            align: 'center',
            fixed: 'left',
            templet: e => TableOP.fieldFormat(e.orderId, "orderId")
        },
        {field: 'orderAmount', title: '订单金额', align: 'right', templet: e => Fen2Yuan(e.orderAmount)},
        {field: 'receiptAmount', title: '实收金额', align: 'right', templet: e => Fen2Yuan(e.receiptAmount)},
        {
            field: 'customerName',
            title: '客户',
            align: 'center',
            templet: e => TableOP.fieldFormat(e.customerName, "customerName")
        },
        {
            field: 'fcCompanyName',
            title: '厂商',
            align: 'center',
            templet: e => TableOP.fieldFormat(e.fcCompanyName, "fcCompanyName")
        },
        {
            field: 'payStatus',
            title: '订单收付状态',
            align: 'center',
            templet: e => TableOP.fieldFormat(e.payStatus, "payStatus")
        },
        {
            field: 'customerStatementId',
            title: '厂商结算单号',
            align: 'center',
            templet: e => TableOP.companyFieldForamt(e.customerStatementId, "customerStatementId", e.fcCompanyId)
        },
        {
            field: 'customerBillCost',
            title: '厂商收款',
            align: 'right',
            templet: e => TableOP.companyFieldForamt(e.customerBillCost, "customerBillCost", e.fcCompanyId)
        },
        {
            field: 'settlementType',
            title: '厂商类型',
            align: 'center',
            templet: e => TableOP.companyFieldForamt(e.settlementType, "settlementType", e.fcCompanyId)
        },
        {
            field: 'customerBillStatus',
            title: '厂商/收款状态',
            align: 'center',
            templet: e => TableOP.companyFieldForamt(e.customerBillStatus, "customerBillStatus", e.fcCompanyId)
        },
        {
            field: 'spCompanyName',
            title: '服务商',
            align: 'center',
            templet: e => TableOP.fieldFormat(e.spCompanyName, "spCompanyName")
        },
        {
            field: 'manageStatementId',
            title: '服务商结算单号',
            align: 'center',
            templet: e => TableOP.fieldFormat(e.manageStatementId, "manageStatementId")
        },
        {field: 'manageSettleCost', title: '服务商提留', align: 'right', templet: e => Fen2Yuan(e.manageSettleCost)},
        {
            field: 'partBillStatus',
            title: '服务商/付款状态',
            align: 'center',
            templet: e => TableOP.fieldFormat(e.partBillStatus, "partBillStatus")
        },
        {
            field: 'accountTime',
            title: '算账时间',
            align: 'center',
            templet: e => TableOP.timeStampTODateStr(e.accountTime)
        }]],
    payStatus: {
        "1": "未支付",
        "2": "支付中",
        "3": "部分支付",
        "4": "已支付",
        "12": "退款中",
        "13": "部分退款",
        "14": "已退款"
    },
    partBillStatus: {
        "10": "待审核",
        "20": "待付款",
        "30": "付款中",
        "40": "已付款",
        "41": "付款失败",
        "100": "待审核",
        "200": "审核通过",
        "210": "审核未过"
    },
    settlementType: {
        "1": "预充值",
        "2": "后结算"
    },
    timeStampTODateStr: function (value) {
        if (!value) {
            return "--";
        }
        value = value * 1000;
        var date = new Date(value).Format('yyyy-MM-dd hh:mm:ss');
        return date.toString();
    },
    companyFieldForamt: function (value, field, companyId) {

        if (!value || !companyId) {
            return "--"
        }
        if (companyId != -100 && companyId <= 0) {
            return "--";
        }
        if (field == "customerBillStatus") {
            if (TableOP.partBillStatus[value]) {
                return TableOP.partBillStatus[value]
            }
        }
        if (field == "customerBillCost") {
            return Fen2Yuan(value);
        }
        if (field == "settlementType") {
            if (TableOP.settlementType[value]) {
                return TableOP.settlementType[value]
            }
        }
        return value;

    },
    fieldFormat: function (value, type) {
        if (type == "orderId") {
            if (!value) {
                return '汇总';
            } else {
                return value;
            }
        }
        if (type == "payStatus") {
            if (TableOP.payStatus[value]) {
                return TableOP.payStatus[value]
            }
        }
        if (type == "customerBillStatus" || type == "partBillStatus") {
            if (TableOP.partBillStatus[value]) {
                return TableOP.partBillStatus[value]
            }
        }

        if (!value) {
            return "--";
        }
        return value;
    }
}
;

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

/**
 * 获取时间，近intervalDays天
 * @param dateNow
 * @param intervalDays
 * @param bolPastTime
 * @returns {Array}
 */
function getDateRange(dateNow, intervalDays, bolPastTime) {
    var oneDayTime = 24 * 60 * 60 * 1000;
    var list = [];
    var lastDay;

    if (bolPastTime == true) {
        lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime);
        list.push(formateDate(lastDay));
        list.push(formateDate(dateNow));
    } else {
        lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime);
        list.push(formateDate(dateNow));
        list.push(formateDate(lastDay));
    }
    return list;
}

function formateDate(time) {
    var year = time.getFullYear()
    var month = time.getMonth() + 1
    var day = time.getDate()
    if (month < 10) {
        month = '0' + month
    }
    if (day < 10) {
        day = '0' + day
    }
    return year + '-' + month + '-' + day + '';
}

/**
 * 格式化公司列表列表项
 * @param {object} repo
 * @returns {string}
 */
function formatRepoForCompany(repo) {
    if (repo.loading) {
        return '查询中...'
    }
    var name = repo.text + (repo.disabled ? '（禁用）' : '');
    var markup = '<div><div><i class="zmn-icon zmn-icon-user"></i><span>' + name + '</span></div></div>';

    return markup;
}

function Fen2Yuan(numstr) {
    if (!numstr || numstr == 0) {
        return "--";
    }
    Number.prototype.div = function (arg) {
        var t1 = 0, t2 = 0, r1, r2;
        try {
            t1 = this.toString().split(".")[1].length
        } catch (e) {
        }
        try {
            t2 = arg.toString().split(".")[1].length
        } catch (e) {
        }
        with (Math) {
            r1 = Number(this.toString().replace(".", ""));
            r2 = Number(arg.toString().replace(".", ""));
            return (r1 / r2) * pow(10, t2 - t1);
        }
    };
    var num = Number(numstr);
    return money_format((num.div(100)).toFixed(2));
}

function getLastWeekDate(myDate) {
    var list = [];
    //var myDate = new Date();
    // 获取上一周的开始和结束时间
    var weekDate = new Date(myDate.getTime() - 7 * 24 * 3600 * 1000);// 计算开始时间用
    var weekDate2 = new Date(myDate.getTime() - 7 * 24 * 3600 * 1000);// 计算结束时间用

    var day = weekDate.getDay();
    var time = weekDate.getDate() - day + (day === 0 ? -6 : 1);

    var startDate = new Date(weekDate.setDate(time));
    var beginTime = startDate.getFullYear() + '-' + (startDate.getMonth() + 1) + '-' + startDate.getDate();
    var endDate = new Date(weekDate2.setDate(time + 6));
    var endTime = endDate.getFullYear() + '-' + (endDate.getMonth() + 1) + '-' + endDate.getDate();

    list.push(beginTime);
    list.push(endTime);
    return list;

}

function money_format(value) {
    if (value == 0) {
        return "--";
    }
    return number_format(value, 2, ".", ",");
}

/**
 * 金额格式化
 * @param number
 * @param decimals
 * @param dec_point
 * @param thousands_sep
 * @returns {string}
 */
function number_format(number, decimals, dec_point, thousands_sep) {
    /*
    * 参数说明：
    * number：要格式化的数字
    * decimals：保留几位小数
    * dec_point：小数点符号
    * thousands_sep：千分位符号
    * */
    number = (number + '').replace(/[^0-9+-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.ceil(n * k) / k;
        };

    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    var re = /(-?\d+)(\d{3})/;
    while (re.test(s[0])) {
        s[0] = s[0].replace(re, "$1" + sep + "$2");
    }

    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

/**
 * 月初
 * @returns {Date}
 * @constructor
 */
function currentMonthFirst(date) {
    date.setDate(1);
    return date;
}

/**
 * 月末
 * @returns {Date}
 */
function currentMonthLast(date) {
    var currentMonth = date.getMonth();
    var nextMonth = ++currentMonth;
    var nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
    var oneDay = 1000 * 60 * 60 * 24;
    return new Date(nextMonthFirstDay - oneDay);
}

layui.extend({
    select: "perf/perf.select",
    formSelects: "{/}/static/lay/lay_extend/formSelects-v4/formSelects-v4.min"
}).define(FormOp.layuiList, FormOp.initLayUiOpt);
